package com.example.teadoctor;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.media.Image;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.support.v4.view.PagerAdapter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import android.support.v4.view.ViewPager;
import android.os.Handler;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;

import java.util.Timer;
import java.util.TimerTask;


public class HeadlinesFragment extends Fragment {
    String headline_title,headline_time,headline_source, headline_text, headline_author, headline_imageurl,record;
    private MyPagerAdapter myPagerAdapter;
    private List<Integer> imageResIds = new ArrayList<>(); // 存储图片资源 ID 的列表
    private List<MyItem> mItemList = new ArrayList<>();
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.page_headlines,container,false);
        ListView listView = view.findViewById(R.id.Pst_my_headlines);
        // 获取TeaDBHelper对象
        TeaDBHelper dbHelper = new TeaDBHelper(getActivity());
        // 获取SQLiteDatabase对象
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        // 初始化 ViewPager
        final ViewPager viewPager = view.findViewById(R.id.view_pager);
        imageResIds.add(R.drawable.image1);
        imageResIds.add(R.drawable.image2);
        imageResIds.add(R.drawable.image3);
        myPagerAdapter = new MyPagerAdapter(imageResIds);
        viewPager.setAdapter(myPagerAdapter);
        final Handler handler = new Handler();
        final Runnable update = new Runnable() {
            public void run() {
                int currentPage = viewPager.getCurrentItem(); // 获取当前页面
                int nextPage = (currentPage + 1) % imageResIds.size(); // 计算下一个页面的位置
                viewPager.setCurrentItem(nextPage, true); // 切换到下一个页面
            }
        };
        Timer myTimer = new Timer();
        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(update);
            }
        }, 2000, 2000);
        String query = "SELECT * FROM headline";
        Cursor cursor = db.rawQuery(query, null);
        ArrayList<String> dataList = new ArrayList<>();
        final ArrayList<String> titleList = new ArrayList<>();
        final ArrayList<String> urlList = new ArrayList<>();
        while(cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("headline_id"));
            headline_title = cursor.getString(cursor.getColumnIndex("headline_title"));
            headline_time = cursor.getString(cursor.getColumnIndex("headline_time"));
            headline_source = cursor.getString(cursor.getColumnIndex("headline_source"));
            headline_text = cursor.getString(cursor.getColumnIndex("headline_text"));
            headline_imageurl = cursor.getString(cursor.getColumnIndex("headline_imageurl"));
            headline_author = cursor.getString(cursor.getColumnIndex("headline_author"));
            record = id + "   " + headline_author + "  " + headline_time + "  " + headline_source;
            dataList.add(record);
            urlList.add(headline_imageurl);
            titleList.add(headline_title);
        }
        final ImageView imageView = view.findViewById(R.id.image_view);
        ImageRequest imageRequest = new ImageRequest(headline_imageurl, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap bitmap) {
                // 将服务器的图片设置到 ImageView 中
                imageView.setImageBitmap(bitmap);
            }
        }, 0, 0, ImageView.ScaleType.CENTER_CROP, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // 请求出错时，什么也不做
            }
        });

        /*int[] array={R.drawable.head1,R.drawable.head2,R.drawable.head3,
                R.drawable.head4,R.drawable.head5,R.drawable.head6,
                R.drawable.head7,R.drawable.head8,R.drawable.head9,R.drawable.head10};*/
        for (int i = 0; i < 10; i++) {
            mItemList.add(new MyItem(titleList.get(i), urlList.get(i),dataList.get(i)));
        }
        MyListAdapter adapter = new MyListAdapter();
        listView.setAdapter(adapter);
        // 点击记录跳转，要传递数据过去，具体展示
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // 解析记录中的数据
                String headline_title = titleList.get(position);

                // 将茶名通过intent传递给要跳转的页面
                Intent intent = new Intent(getActivity(), newinfo.class);
                intent.putExtra("headline_title", headline_title);
                startActivity(intent);
            }
        });
        // 关闭结果集和数据库连接
        cursor.close();
        db.close();
        return view;
    }
    //listview适配器
    private class MyListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mItemList.size();
        }

        @Override
        public Object getItem(int position) {
            return mItemList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_layout, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.titleTextView = convertView.findViewById(R.id.text_view);
                viewHolder.dateTextView = convertView.findViewById(R.id.text_view1);
                viewHolder.imageView = convertView.findViewById(R.id.image_view);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            MyItem item = mItemList.get(position);
            viewHolder.titleTextView.setText(item.getTitle());
            viewHolder.dateTextView.setText(item.getDate());
            ImageRequest imageRequest = new ImageRequest(item.getImageUrl(), new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap bitmap) {
                    // 将服务器的图片设置到 ImageView 中
                    viewHolder.imageView.setImageBitmap(bitmap);
                }
            }, 0, 0, ImageView.ScaleType.CENTER_CROP, null, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // 请求出错时，什么也不做
                }
            });
            // 使用 Volley 请求服务器的图片
            RequestQueue requestQueue = Volley.newRequestQueue(getContext());
            requestQueue.add(imageRequest);

            return convertView;
        }

        private  class ViewHolder {
            TextView titleTextView;
            TextView dateTextView;
            ImageView imageView;
        }
    }

    //.....
    public class MyItem {
        private String title;
        private String imageUrl;    // 保存图片链接
        private String date;

        public MyItem(String title, String imageUrl, String date) {
            this.title = title;
            this.imageUrl = imageUrl;
            this.date = date;
        }

        public String getTitle() {
            return title;
        }

        public String getImageUrl() {
            return imageUrl;
        }

        public String getDate() {
            return date;
        }
    }

    //适配器
    public class MyPagerAdapter extends PagerAdapter {

        private List<Integer> mImageResIds;

        public MyPagerAdapter(List<Integer> imageResIds) {
            mImageResIds = imageResIds;
        }

        @Override
        public int getCount() {
            return mImageResIds.size();
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView imageView = new ImageView(container.getContext());
            // 设置图片填充方式为 CENTER_CROP
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setImageResource(mImageResIds.get(position));
            //container.addView(imageView);
            // 设置 ImageView 的宽高为 MATCH_PARENT，以充满 ViewPager
            container.addView(imageView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            return imageView;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }
}
